import store from '@/store';
import ajax from '@/utils/ajax.js' // #ifdef H5
// #endif
let code = "";
let loginStart = true;
let userInfo = {
	token: ""
};
let tag = true;
let lastPageUrl = "";
// 微信小程序登录
function onLogin(type = "judge", callback) {
	//判断登录状态
	if (loginStart) {
		lastPageUrl = "";
		loginStart = false;
		const _this = this;
		let platform;
		// #ifdef MP-WEIXIN
		platform = 'weixin';
		// #endif
		// #ifdef MP-ALIPAY
		platform = 'alipay';
		// #endif
		// #ifdef MP-BAIDU
		platform = 'baidu';
		// #endif
		uni.login({
			provider: platform,
			success: function(loginRes) {
				if (loginRes.errMsg == 'login:ok') {
					code = loginRes.code;
					// 获取用户信息
					uni.getUserInfo({
						provider: platform,
						success: function(infoRes) {
							console.log(infoRes)
							getUserInfo(infoRes, "", callback);
						},
						fail() {
							if (type != "try") {
								store.commit('setLoginPopupShow', true);
								Object.defineProperty(userInfo, "token", {
									get: function(val) {
										return {};
									},
									set: function(newVal) {
										callback && callback();
									}
								});
								setTimeout(() => {
									loginStart = true;
								}, 2000);
							} else {
								loginStart = true;
							}
						}
					});
				}
			}
		});
	}
}

function wxLogin(callbacks) {
	let callback = callbacks;
	if (tag) {
		tag = false;
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				if (loginRes.errMsg == 'login:ok') {
					code = loginRes.code;
					// 获取用户信息
					uni.showModal({
						title: '温馨提示',
						content: '亲，授权微信登录后才能正常使用小程序功能',
						success(res) {
							if (res.confirm) {
								uni.getUserProfile({
										desc: '用于完善个人资料' // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
									})
									.then((response) => {
										if (response[1].errMsg === 'getUserProfile:ok') {
											uni.setStorageSync('userInfo', response[1]
												.userInfo); //存储用户信息
											getUserInfo(response[1], "", callback); //返回的信息 
											tag = true;
										} else {
											tag = true;
											uni.showToast({
												title: '授权失敗',
												icon: 'error'
											});
										}
									}).catch((reject) => {
										tag = true;
										console.log('拒绝授权', reject)
									})
							} else if (res.cancel) {
								tag = true;
								uni.showToast({
									title: '授权失敗',
									icon: 'error'
								});
							}
						}
					})
				}
			}
		});
	}
}
//微信小程序获取用户信息
function getUserInfo(info, type, callbacks) {
	let callback = callbacks;
	let httpData = {
		username: info.userInfo.nickName,
		nickname: info.userInfo.nickName,
		iv: info.iv,
		encryptedData: info.encryptedData,
		code: code,
		avatar: info.userInfo.avatarUrl
	};
	// store.state.chatScenesInfo里面是小程序二维码附带的信息
	if (store.state.chatScenesInfo.recommendCode) {
		// 推荐码
		httpData.recommendUid = store.state.chatScenesInfo.recommendCode;
	}
	ajax.post('/user/wxlogin', httpData).then(es => {
		loginStart = true;
		let res = es.data
		store.commit('setUserInfo', res);
		if (type == "authorized") {
			userInfo.token = res.token;
			store.commit('setLoginPopupShow', false);
		}
		uni.showToast({
			title: "登录成功"
		});
		uni.switchTab({
			url: '/pages/user/index'
		})


	}, err => {
		loginStart = true;
	});
}
//判断是否登录（所有端）
function judgeLogin(callback, type = "judge") {
	if (store.state.chatScenesInfo.scene == 1154) {
		uni.showToast({
			title: '请前往小程序使用完整服务',
			icon: "none"
		});
	} else {
		let storeUserInfo = store.state.userInfo;
		if (!storeUserInfo.token) { // nvue页面读取不到vuex里面数据，将取缓存
			storeUserInfo = uni.getStorageSync("userInfo");
		}
		if (type != "force" && storeUserInfo.token && '' != storeUserInfo.token) {
			callback(storeUserInfo);
		} else if (storeUserInfo.token && !storeUserInfo.phone) {
			if (type == "force") {
				uni.navigateTo({
					url: '/pages/user/bindPhone'
				});
			} else {
				uni.showModal({
					title: "提示",
					content: "您还未绑定手机号，请先绑定~",
					confirmText: "去绑定",
					cancelText: "再逛会",
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/user/bindPhone'
							});
						}
					}
				});
			}
		} else {
			// #ifdef MP
			wxLogin(type, callback);
			// #endif
			// #ifdef APP-PLUS
			uni.showModal({
				title: "登录提示",
				content: "此时此刻需要您登录喔~",
				confirmText: "去登录",
				cancelText: "再逛会",
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: "/pages/map/user/login"
						});
					}
				}
			});
			// #endif
			// #ifdef H5
			// #endif
		}
	}
}
export {
	onLogin,
	wxLogin,
	getUserInfo,
	judgeLogin
}
